<template>
    <PopUps :bgIndex="1000" :boxIndex="1001" widthMy='60%'  height-my="78%">
        <div class="addManage-box">
            <div class="header">
                <div class="header-top">
                    <h3>客户基础信息</h3>
                    <i class="iconfont icon-icon-cross-empty" @click="closePopUps"></i>
                </div>
                <div class="headerMain">
                    <el-form ref="formRef" :inline="true" :model="addManage" :rules="flagRules ? rules : {}"
                        class="demo-form-inline">
                        <el-form-item :prop="item.name" :label="item.label" v-for="(item, index) in addManageLabel"
                            :key="index" :style="{ 'min-width': `${item.minWidth}'!important'` }">
                            <!-- 输入框 -->
                            <el-input v-model="addManage[item.name]" clearable v-if="!item.type || item.type == 'input'"
                                :disabled="props.contactFlag || props.classifyFlag || item.disabled || defindDisabled" />
                            <!-- 下拉选框 -->
                            <el-select v-model="addManage[item.name]" clearable v-if="item.type == 'select'"
                                :disabled="item.disabled ? props.contactFlag : props.classifyFlag || props.contactFlag || defindDisabled">
                                <el-option :label="item1.label" :value="item1.value" v-for="(item1, index) in item.client"
                                    :key="index" />
                            </el-select>
                            <!-- 日期选框 -->
                            <el-date-picker v-else-if="item.type == 'picker'" v-model="addManage[item.name]" type="date"
                                :disabled="props.contactFlag || props.classifyFlag || defindDisabled" placeholder="请输入日期"
                                format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
                            <!-- 部门 -->
                            <el-tree-select v-else-if="item.type == 'tree'" v-model="addManage[item.name]" :data="props.deptOptions"
                                :disabled="props.contactFlag || props.classifyFlag || defindDisabled"
                                :props="{ value: 'id', label: 'label', children: 'children' }" value-key="id"
                                placeholder="请选择归属部门" check-strictly />
                        </el-form-item>
                    </el-form>
                </div>
            </div>
            <div class="main">
                <div class="main-top">
                    <h3>开票信息</h3>
                </div>
                <div class="mainContent">
                    <div class="content-lable label-flex">
                        <p class="lable-p">工商注册名称</p>
                        <el-input v-model="invoiceInfo.gongshangRegisteredName"
                            :disabled="props.contactFlag || props.classifyFlag || defindDisabled" />
                    </div>
                    <div class="content-lable label-flex">
                        <p class="lable-p">开户银行</p>
                        <el-input v-model="invoiceInfo.bankDeposit"
                            :disabled="props.contactFlag || props.classifyFlag || defindDisabled" />
                    </div>
                    <div class="content-lable label-flex">
                        <p class="lable-p">税号</p>
                        <el-input v-model="invoiceInfo.taxIdentificationNumber"
                            :disabled="props.contactFlag || props.classifyFlag || defindDisabled" />
                    </div>
                    <div class="content-lable label-flex">
                        <p class="lable-p">注册电话</p>
                        <el-input v-model="invoiceInfo.registeredAddressPhone"
                            :disabled="props.contactFlag || props.classifyFlag || defindDisabled" />
                    </div>
                </div>
            </div>
            <div class="floor">
                <div class="floor-top">
                    <h3>客户其他联系人</h3>
                </div>
                <div class="floor-content">
                    <customerTable :tableHeaderData="tableHeaderData" :tableData="tableData" :operate="true" :bg="'#F6F8FE'"
                        @handleDelete="handleDelete" :disabled="props.classifyFlag || defindDisabled" />
                    <div class="addTable">
                        <span @click="addTable">增加一行</span>
                    </div>
                    <div class="content-lable label-flex remarks-box">
                        <p class="lable-p remarks">备注</p>
                        <el-input v-model="invoiceInfo.remarks" type="textarea"
                            :disabled="props.contactFlag || props.classifyFlag || defindDisabled" />
                    </div>
                    <div class="btn">
                        <el-button type="primary" @click="onSubmit(formRef)" class="submit" v-if="props.popTitle != '详情'">{{
                            props.popTitle }}</el-button>
                        <el-button type="primary" @click="closePopUps" class="reset" color="#E4E9FC">取消</el-button>
                    </div>
                </div>
            </div>
        </div>
    </PopUps>
</template>

<script setup>
import PopUps from '@/components/My/PopUps';
import customerTable from './customerTable';
import { ref, reactive, defineEmits, defineProps, onMounted } from 'vue'
import { getdepartmentseApi } from '@/api/tickets/index'
import { ElMessage } from 'element-plus'
import { addInsertCustApi, updateCust, updateCustAlternative, updateCustRankApi } from '@/api/customer'
import { forInValueFn } from '@/hook/forIn.js'
const { forInValue } = forInValueFn()
import { getApiDataRules } from '@/hook/getApiDataRules'

const { apiRulesData } = getApiDataRules()

const emit = defineEmits(['closePopUps', 'getCustomerData'])
const props = defineProps(['popTitle', 'contactFlag', 'classifyFlag', 'defindPopData','deptOptions'])

const formRef = ref(null)
let flagRules = ref(true)
let defindDisabled = ref(false)
// 客户信息
const addManage = ref({
    customerId: '后台生成',
    primaryClassification: '',    // 一级分类
    customerName: '',    // 客户名称
    office: '',    // 职务
    companyName: '',    // 服务公司
    responsiblePerson: '',    // 负责人
    responsiblePersonPhone: '',    // 负责人电话
    customerType: '',    // 客户类型
    customerRank: 'C中级客户',    // 客户等级
    customerContacts: '',    // 客户联系人
    customerSource: '',    // 客户来源
    contactPhone: '',    // 联系电话
    address: '',    // 联系地址
    deptId: '',    // 部门  
    paymentCycle: '',   // 回款周期
    paymentMethod: '',  // 结款方式
  profitRateMin: '',  // 客户最低利率
})
const addManageLabel = ref([
    {
        name: 'customerId',
        label: '客户编号',
        disabled: true
    },
    {
        name: 'primaryClassification',
        label: '一级分类',
    },
    {
        name: 'customerName',
        label: '客户名称',
    },
    {
        name: 'office',
        label: '职务',
    },
    {
        name: 'companyName',
        label: '服务公司',
    },
    {
        name: 'responsiblePerson',
        label: '负责人',
    },
    {
        name: 'responsiblePersonPhone',
        label: '负责人电话',
    },
    {
        name: 'customerType',
        label: '客户类型',
        type: 'select',
        client: [
            {
                label: '外协流程',
                value: '0'
            },
            {
                label: '标准流程',
                value: '1'
            },
            {
                label: '散客',
                value: '2'
            }
        ]
    },
    {
        name: 'customerRank',
        label: '客户等级',
        type: 'select',
        disabled: props.classifyFlag ? true : false,
        client: [
            {
                label: 'A核心客户',
                value: 'A核心客户'
            },
            {
                label: 'B高级客户',
                value: 'B高级客户'
            },
            {
                label: 'C中级客户',
                value: 'C中级客户'
            },
            {
                label: 'D普通客户',
                value: 'D普通客户'
            },
            {
                label: 'E低价值客户',
                value: 'E低价值客户'
            },
            {
                label: 'F散户',
                value: 'F散户'
            },
        ]
    },
    {
        name: 'customerContacts',
        label: '客户联系人'
    },{
        name: 'profitRateMin',
        label: '客户最低利率'
    },
    {
        name: 'customerSource',
        label: '客户来源',
        type: 'select',
        client: [
            {
                label: '客户介绍',
                value: '0'
            },
            {
                label: '线上广告',
                value: '1'
            },
            {
                label: '线下宣传',
                value: '2'
            },
            {
                label: '电话咨询',
                value: '3'
            },
            {
                label: '展会论坛',
                value: '4'
            },
            {
                label: '公司资源',
                value: '5'
            },
            {
                label: '个人资源',
                value: '6'
            },
            {
                label: '其他',
                value: '7'
            },
        ]
    },
    {
        name: 'contactPhone',
        label: '联系电话',
    },
    {
        name: 'deptId',
        label: '部门',
        type: 'tree',

    },
    {
        name: 'address',
        label: '联系地址',
    },
    // {
    //     name: 'paymentCycle',
    //     label: '回款周期',
    // },
    // {
    //     name: 'paymentMethod',
    //     label: '结款方式',
    // },
    // {
    //     name: 'salePrice',
    //     label: '销售单价',
    // },
])
// 校验
const rules = reactive({
    primaryClassification: [
        {
            required: true,
            message: '一级分类',
            trigger: 'change',
        }
    ],
    customerName: [
        {
            required: true,
            message: '客户名称',
            trigger: 'change',
        }
    ],
    responsiblePerson: [
        {
            required: true,
            message: '负责人',
            trigger: 'change',
        }
    ],
    customerType: [
        {
            required: true,
            message: '客户类型',
            trigger: 'change',
        }
    ],
    customerContacts: [
        {
            required: true,
            message: '客户联系人',
            trigger: 'change',
        }
    ],
    responsiblePersonPhone: [
        {
            required: true,
            message: '负责人电话',
            trigger: 'change',
        }
    ],
    customerSource: [
        {
            required: true,
            message: '客户来源',
            trigger: 'change',
        }
    ],    profitRateMin: [
        {
            required: true,
            message: '客户最低利率',
            trigger: 'change',
        }
    ],
    contactPhone: [
        {
            required: true,
            message: '联系电话',
            trigger: 'change',
        },
        {
            pattern: /^(?:(?:\+|00)86)?1[3-9]\d{9}$/, message: '手机号码格式不正确', trigger: 'blur'
        }
    ],
    deptId: [
        {
            required: true,
            message: '部门',
            trigger: 'change',
        }
    ],
    paymentCycle: [
        {
            required: true,
            message: '回款周期',
            trigger: 'change',
        }
    ],
    paymentMethod: [
        {
            required: true,
            message: '结款方式',
            trigger: 'change',
        }
    ],
})
// 开票信息
const invoiceInfo = ref({
    gongshangRegisteredName: '',    // 工商注册名称
    bankDeposit: '',                //  开户银行
    taxIdentificationNumber: '',    //  税号
    registeredAddressPhone: '',     // 注册电话
    remarks: '',                    // 备注
})
// 客户其他联系人
// 表格头部
const tableHeaderData = ref([
    {
        prop: 'name',
        label: '姓名',
        width: '150px'
    },
    {
        prop: 'gender',
        label: '性别',
        width: '150px'
    },
    {
        prop: 'office',
        label: '职务',
        width: '150px'
    },
    {
        prop: 'dept',
        label: '部门',
        width: '150px'
    },
    {
        prop: 'contactPhone',
        label: '联系电话',
        width: '150px'
    },
    {
        prop: 'alternativeAddress',
        label: '地址',
        colorClassName: 'addressInput',
        width: '300px'
    },
])


// 表格内容
const tableData = ref([
    {
        name: '',       // 姓名
        gender: '',     // 性别
        office: '',     // 职务
        dept: '',       // 部门
        contactPhone: '',   // 联系电话
        alternativeAddress: '',        //地址
    }
])


// 新增一行表格
const addTable = () => {
    tableData.value.push({
        name: '',
        gender: '',
        office: '',
        dept: '',
        contactPhone: '',
        alternativeAddress: '',
    })
}
// 删除一行表格
const handleDelete = (props) => {
    if (tableData.value.length > 1) {
        tableData.value.splice(props.i, 1)
    } else {
        ElMessage({
            type: 'warning',
            message: '再删就没有了(*——*)',
        })
    }
}
// 新增
const onSubmit = async (formRef) => {
    if (!formRef) return
    await formRef.validate((valid) => {
        if (valid) {
            if (props.popTitle == "新增") {
                // 发送新增请求
                addManage.value.customerId = ''
                let params = Object.assign(addManage.value, invoiceInfo.value)
                params.custAlternativeVOS = tableData.value
                addInsertCustApi(params).then(res => {
                    addManage.value.customerId = '后台生成'
                    if (res.code == 200) {
                        emit('getCustomerData')
                        closePopUps()
                        ElMessage({
                            type: 'success',
                            message: res.msg,
                        })
                    }
                })
            } else if (props.popTitle == "修改") {
                // 发送修改
                let params = Object.assign(addManage.value, invoiceInfo.value)
                params.custAlternativeVOS = tableData.value
              params.custAlternativeVOS.forEach((item, index) => {
                item.customerId =params.customerId
              })
                updateCust(params).then(res => {
                    if (res.code == 200) {
                        emit('getCustomerData')
                        closePopUps()
                        ElMessage({
                            type: 'success',
                            message: res.msg,
                        })
                    }
                })
            } else if (props.popTitle == '修改等级') {
                let params = {
                    "customerId": addManage.value.customerId,
                    "customerRank": addManage.value.customerRank
                }

              updateCustRankApi(params).then(res => {
                    if (res.code == 200) {
                        emit('getCustomerData')
                        closePopUps()
                        ElMessage({
                            type: 'success',
                            message: res.msg,
                        })
                    }
                })


            } else if (props.popTitle == '修改联系人') {
              let params = props.defindPopData.custAlternativeVOS
              if(params[0].customerId){
                params.forEach((item, index) => {
                  item.customerId =params[0].customerId
                })
              }
                updateCustAlternative(params).then(res => {
                    if (res.code == 200) {
                        emit('getCustomerData')
                        closePopUps()
                        ElMessage({
                            type: 'success',
                            message: res.msg,
                        })
                    }
                })
            }

        }
    })

}
// 关闭
const closePopUps = () => {
    emit('closePopUps')
}
// 数据回显
const assignmentFun = () => {
    // 表单
    if (props.popTitle == '详情') {
        defindDisabled.value = true
    }
    flagRules.value = false
    forInValue(addManage, props.defindPopData)
    forInValue(invoiceInfo, props.defindPopData)
    tableData.value = props.defindPopData.custAlternativeVOS
}

onMounted(() => {
    if (Object.keys(props.defindPopData).length != 0) {
        assignmentFun()
    }
})
</script>

<style scoped lang="scss">
@import '@/assets/styles/mixin.scss';

@mixin flex {
    display: flex;
    align-items: center;
    margin-bottom: 18px;
}

@mixin titlePadding {
    padding: 25px 25px 25px 45px;
}


.demo-form-inline .el-select {
    --el-select-width: 220px;
}

:deep(.el-input) {
    width: 120px;
}

.form-inline {
    :deep(.el-form-item__label) {
        width: 80px;
    }

    :deep(.el-form-item) {
        width: 190px;
    }
}

.el-input__wrapper {
    --el-select-width: 220px;
}

:deep(.el-form-item) {
    width: 200px !important;
}

:deep(.el-form-item__label) {
    width: 120px;
    text-align: right;
}

:deep(.el-textarea) {
    width: 140px;
}

.optionsInput {
    display: flex;

    .btn {
        background-color: #829BFF;
        color: #fff;
    }
}

.label-flex {
    @include flex
}

.lable-p {
    @include label
}



.addManage-box {
    .header {
        .header-top {
            @include titlePadding;
            display: flex;
            align-items: center;
            justify-content: space-between;
            position: sticky;
            top: 0px;
            background: #fff;
            z-index: 2024;

            h3 {
                @include publicH3;
            }

            .iconfont {
                color: #666;
                font-size: 27px;
            }
        }

        .headerMain {

            .demo-form-inline {
                @include pubilcForm;
            }
        }
    }

    .main {
        .main-top {
            @include titlePadding;

            h3 {
                @include publicH3;
            }
        }

        .mainContent {
            padding: 0 20px;
            display: flex;
            align-items: center;
            flex-wrap: wrap;

            :deep(.el-input) {
                width: 330px;
            }

            .remarks {
                width: 400px;
            }

            .demo-form-inline {
                margin-top: 20px;
                @include pubilcForm;

            }
        }
    }

    .floor {
        .floor-top {
            @include titlePadding;

            h3 {
                @include publicH3;
            }
        }

        .floor-content {
            padding: 0 20px;

            .addTable {
                width: 100%;
                text-align: right;
                margin: 20px 0;
                color: #1947FF;
                cursor: pointer;
            }

            .remarks-box {
                .remarks {
                    width: 63px;
                }

                :deep(.el-input) {
                    width: 330px;
                }
            }
        }

        .btn {
            text-align: right;
            margin-bottom: 20px;

            .reset {
                color: #333;
                border: none;
            }
        }
    }
}
</style>